<?php
namespace app\home\logic;

use think\Model;

class User extends Model {
    public function login($username, $pwd) {
        if (!$username || !$pwd) {
            return $this->loginCode(6);
        }
        $userModel = model('user');
        $where ['phone|username'] = $username;
        $user = $userModel->getUser($where);
        $session_name = 'login_error_number_' . $username;
        $login_error_number = session('?' . $session_name) ? session($session_name) : 0;

        if ($login_error_number >= 5) {
            return $this->loginCode(7);
        }

        if (!$user) {
            session($session_name, $login_error_number+1);
            return $this->loginCode(2);
        }
        if ($user['password'] != md5($pwd)) {
            session($session_name, $login_error_number+1);
            return $this->loginCode(3);
        }
        if ($user['block_status'] == 1) {
            return $this->loginCode(4);
        }

        //更新用户登录信息
        $re = $userModel->updateUserLogin($user['user_id']);
        if (!$re) {
            return $this->loginCode(5);
        }

        //加入用户操作记录
        model('users_log')->AddUsersLog([
                'user_id' => $user['user_id'],
                'code' => 'users',
                'type' => 'action',
                'operating' => 'login',
                'article_id' => $user['user_id'],
                'result' => 1,
                'content' => date('Y-m-d H:i:s') . ' 登录成功'
        ]);

        //记录cookie
        $cdata['user_id'] = $user['user_id'];
        $cdata['cookie_status'] = config('con_cache_type'); //1:cookie 0:session
        $cdata["cookie_id"] = config('con_cookie_id');
        $cdata['time'] = $cdata['cookie_status'] == 1 ? 1800 : 86400;
        SetCookies($cdata);

        session($session_name, null);
        return $this->loginCode(1, $user['user_id']);
    }

    public function loginCode($code = 1, $uid = '') {
        switch ($code) {
            case 1:
                $msg = '成功';
                break;
            case 2:
                $msg = '用户不存在';
                break;
            case 3:
                $msg = '密码不正确';
                break;
            case 4:
                $msg = '对不起,您的帐号已被锁定,请联系在线客服';
                break;
            case 5:
                $msg = '更新用户登录信息失败!';
                break;
            case 6:
                $msg = '用户名或密码不能为空!';
                break;
            case 7:
                $msg = '账户已被冻结，请24小时后重试或点击“忘记密码”进行重置!';
                break;
            default:
                $msg = '登录失败';
        }
        return ['code' => $code, 'msg' => $msg, 'uid' => $uid];
    }

    public function logout() {
        $data['cookie_status'] = config('con_cache_type'); //1:cookie 0:session
        $data["cookie_id"] = config('con_cookie_id');
        DelCookies($data);
        return ['code' => 1, 'msg' => ''];
    }
}
